/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
/*
 * Created on 24 oct. 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package fr.jade.console.cmd;

import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.Interface;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.BindingController;
import org.objectweb.fractal.api.type.InterfaceType;

import fr.jade.console.core.AbstractCommand;
import fr.jade.console.core.Command;
import fr.jade.console.core.Environment;
import fr.jade.util.FractalNavigator;
import fr.jade.util.FractalUtil;

/**
 * @author Sylvain Sicard
 */
public class Follow extends AbstractCommand implements Command{

  public String getDescription(){
    return "follow a binding";
  }
  
  public String getHelp(){
    return "follow <itfName>\n";
  }
  
  public String getName() {
    return "follow";
  }

	public Object execute(String[] args, Environment env) throws Throwable {

		if(args.length != 2){
		  System.out.println(getHelp());
		}else{
		  String itfName = args[1];
		  Component curent = (Component)env.getEnvVar("current");
		  try{
  		  Interface clientItf= (Interface)curent.getFcInterface(itfName);
  		  InterfaceType clientItfType = (InterfaceType)clientItf.getFcItfType();
  		  if(clientItfType.isFcClientItf()){
  		    BindingController bc = FractalUtil.getBindingController(curent);
  		    Interface serverItf = (Interface)bc.lookupFc(itfName);
  		    if(serverItf == null){
  		      System.out.println(itfName + " is not bound");
  		    }else{
  		      env.setEnvVar("current", serverItf.getFcItfOwner());
  		    }
  		  }else{
  		    System.out.println(itfName + " is not a client interface");
  		  }
		  }catch(NoSuchInterfaceException e){
		    System.out.println(itfName + ": no such interface on component "+FractalNavigator.getName(curent));
		  }
		}
		
		return null;
	}
	
}
